package com.usian.security.controller;

import com.usian.common.modol.Result;
import com.usian.common.util.JwtUtil;
import com.usian.security.entity.LoginUser;
import com.usian.security.entity.User;
import com.usian.security.exception.CustomException;
import com.usian.security.service.UserService;
import com.usian.security.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisUtil redisUtil;
    @PostMapping("/login")
    public Result<Map<String,String>> login(@RequestBody User query){
//        使用AuthenticationManager的认证接口 做用户认证
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(query.getUserName(),query.getPassword());
        Authentication authenticate =authenticationManager.authenticate(authenticationToken);
        if (authenticate==null){
            throw  new CustomException("登录失败");
        }
//        认证成功则通过jwt创建token
        LoginUser loginUser=(LoginUser) authenticate.getPrincipal();
        String token= JwtUtil.createToken(loginUser.getUser().getUserId(),loginUser.getUser().getUserName());
        Map<String,String> data=new HashMap<>();
        data.put("token",token);

//        3.把用户信息存入到redis
        String key="login:"+loginUser.getUser().getUserId();
        if (redisUtil.containsKey(key)){
            redisUtil.del(key);
        }
        redisUtil.set(key,loginUser);
        return Result.createSuccess(data);
    }

    @GetMapping(value = "/hello")
    @PreAuthorize("hasAuthority('sys:admin')")
    public String sayHello(){
        return "hello world";
    }
}
